<?php
/**
* 
*/
abstract class Page
{
	public $totalRow;//总行数
	public $totalPage;//总页数
	public $limit; //每页显示个数
	public $page; //当前页
	public $pre; //前一页
	public $next; //后一页
	public $url; //当前页面的链接地址

	public function init($totalRow,$limit,$page){
		$this->totalRow=$totalRow;
		$this->limit=$limit;
		$this->page=$page;
		$this->getUrl();
		$this->getPre();
		$this->getNext();
	}

	abstract public function getTotalPage();

	abstract public function getUrl();

	abstract public function getPre();

	abstract public function getNext();

	abstract public function render();

}

class MyPage extends Page{
	private $tag;
	//构造方法
	public function __construct($totalRow,$limit,$page){
		$this->init($totalRow,$limit,$page);
		$this->getTotalPage();
	}
	//获得总页数
	public function getTotalPage(){
		$this->totalPage = ceil($this->totalRow/$this->limit);
	}
	//获取当前url
	public function getUrl()
	{
		$matches=$_GET;
		if(isset($matches['page'])){
			unset($matches['page']);
		}
		if(!empty($matches)){
			$this->url=$_SERVER['SCRIPT_NAME'].'?'.http_build_query($matches);
			$this->tag='&';
		}else{
			$this->url=$_SERVER['SCRIPT_NAME'];
			$this->tag='?';
		}
		
	}
	//获取上一页
	public function getPre()
	{
		$this->pre=$this->page-1;
	}
	//获取下一页
	public function getNext()
	{
		$this->next=$this->page+1;
	}
	//获取分页HMTL
	public function render()
	{	
		//要返回的Html字符串
		$html='';
		//首页
		$html.='<a href="'.$this->url.$this->tag.'page=1" class="btn btn-success">首页</a> ';
		//上一页
		if($this->pre>0){
			$html.='<a href="'.$this->url.$this->tag.'page='.$this->pre.'" class="btn btn-success">上一页</a> ';
		}
		//循环打印页码
		for ($i=1; $i <=$this->totalPage ; $i++) { 
			$html.='<a href="'.$this->url.$this->tag.'page='.$i.'" class="btn btn-success">'.$i.'</a> ';
		}
		//下一页
		if($this->next<=$this->totalPage){
			$html.='<a href="'.$this->url.$this->tag.'page='.$this->next.'" class="btn btn-success">下一页</a> ';
		}
		$html.='<a href="'.$this->url.$this->tag.'page='.$this->totalPage.'" class="btn btn-success">末页</a> ';
		return $html;

	}



}

// print_r($_SERVER);
// if(isset($_GET['page'])&&$_GET['page']>0){
// 	$page=$_GET['page'];
// }else{
// 	$page=1;
// }
// $p = new MyPage(100,10,$page);
// echo $p->render();